<template>
  <MainLayout title="环境管理">
    <template #main>
      <div class="main_block">
        <SearchLayout>
          <template #search>
            <el-input
              v-model="search_params.queryParams.envName"
              placeholder="请输入环境名"
              clearable
              class="search_item"
            />
            <el-button type="primary" @click="handleSearchList('saerch')"
              >搜索</el-button
            >
            <el-button @click="handleSearchReset">重置</el-button>
            <el-button type="success" @click="handleAddUser"
              >新增环境</el-button
            >
          </template>
          <template #table>
            <el-table
              :data="table_list"
              border
              v-loading="table_loading"
              :style="{ height: 'calc(100vh - 260px)' }"
            >
              <el-table-column
                label="序号"
                width="55"
                type="index"
                align="center"
              />
              <el-table-column
                prop="envName"
                label="环境名称"
                min-width="120"
                align="center"
              />
              <el-table-column
                prop="default"
                label="是否默认"
                min-width="100"
                align="center"
              >
                <template #default="{ row }">
                  <el-switch
                    :model-value="row.default"
                    size="small"
                    :active-value="true"
                    :inactive-value="false"
                    @change="handleDefaultChange(row)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="envPath"
                label="环境路径"
                min-width="150"
                align="center"
              >
              </el-table-column>
              <el-table-column label="操作" width="100" align="center">
                <template #default="{ row }">
                  <div class="flex_block_around operate_block">
                    <div
                      class="color_primary cursor_pointer"
                      @click="handleEdit(row)"
                    >
                      编辑
                    </div>
                    <div
                      class="color_delete cursor_pointer"
                      @click="handleDelete(row)"
                    >
                      删除
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <Pagination
              :page="search_params.pageNum"
              :size="search_params.pageSize"
              :total="table_total"
              @change="handlePaginationChange"
            ></Pagination>
          </template>
        </SearchLayout>
      </div>
    </template>
  </MainLayout>
  <el-dialog
    v-model="isShowDialog"
    :title="`${dialog_state ? '新增' : '编辑'}环境`"
    width="1000"
    :before-close="handleDialogClose"
    :close-on-click-modal="false"
  >
    <div class="dialog_main">
      <el-form
        ref="form_ref"
        :model="form_params"
        label-width="100"
        :rules="form_rules"
        style="max-width: 1000px"
      >
        <el-form-item label="环境名称：" prop="envName">
          <el-input
            v-model="form_params.envName"
            clearable
            placeholder="请输入环境名称"
          />
        </el-form-item>
        <el-form-item label="环境配置：">
          <YamlEditor
            style="width: 100%"
            v-model="form_params.envValue"
            @handleError="handleYamlError"
          ></YamlEditor>
        </el-form-item>
        <el-form-item label="示例：">
          <div class="example" @click="handleExample">示例.yaml</div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button
          type="primary"
          :loading="form_loading"
          @click="handleDialogConfirm"
          :disabled="yaml_error"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  AdminEnvironmentList,
  AdminEnvironmentAdd,
  AdminEnvironmentEdit,
  AdminEnvironmentDelete,
} from "@/api/settings.js";
import { nextTick, ref } from "vue";
import { iso8601ToTime } from "@/utils/index.js";

const search_params = reactive({
  pageNum: 1,
  pageSize: 10,
  queryParams: {
    envName: "",
  },
});
const table_loading = ref(false);
const table_total = ref(0);
const table_list = ref([]);
const isShowDialog = ref(false);
const dialog_state = ref(true);
const form_params = reactive({
  envPath: null,
  envName: "",
  envOriginName: "",
  envValue: "",
  default: false,
});
const form_rules = reactive({
  envName: [{ required: true, message: "请输入环境名称", trigger: "blur" }],
  envValue: [{ required: true, message: "请输入环境配置", trigger: "blur" }],
});
const edit_info = ref({});
// yaml的格式如果有误就不能提交
const yaml_error = ref(false);

onMounted(() => {
  handleSearchList(); //获取列表数据
});

const handleSearchReset = () => {
  search_params.queryParams.envName = "";
  handleSearchList();
};
const handleSearchList = (type) => {
  if (type === "search") {
    search_params.page = 1;
  }
  table_loading.value = true;
  AdminEnvironmentList(search_params)
    .then((res) => {
      table_list.value = res.list;
      table_total.value = res.total;
    })
    .finally(() => {
      table_loading.value = false;
    });
};
const handlePaginationChange = (value) => {
  search_params.pageNum = value.page;
  search_params.pageSize = value.size;
  handleSearchList();
};
const form_ref = ref(null);
const form_loading = ref(false);

const handleAddUser = () => {
  edit_info.value = {};
  form_params.envPath = null;
  form_params.envOriginName = "";
  form_params.envName = "";
  form_params.envValue = "";
  form_params.default = false;
  isShowDialog.value = true;
};
const handleEdit = (item) => {
  edit_info.value = JSON.parse(JSON.stringify(item));
  form_params.envOriginName = edit_info.value.envName;
  form_params.envName = edit_info.value.envName;
  form_params.envValue = edit_info.value.envValue || "";
  form_params.envPath = edit_info.value.envPath;
  form_params.default = edit_info.value.default;
  dialog_state.value = false;
  isShowDialog.value = true;
};
const handleDialogClose = () => {
  edit_info.value = {};
  form_params.envPath = null;
  form_params.envOriginName = "";
  form_params.envName = "";
  form_params.envValue = "";
  form_params.default = false;
  nextTick(() => {
    dialog_state.value = true;
    form_ref.value.resetFields();
  });
  isShowDialog.value = false;
};
const handleDialogConfirm = () => {
  form_ref.value.validate((valid) => {
    if (valid) {
      let obj = {};
      if (dialog_state.value) {
        form_loading.value = true;
        delete form_params.envOriginName;
        AdminEnvironmentAdd(form_params)
          .then((res) => {
            handleDialogClose();
            ElMessage.success("环境添加成功");
            handleSearchList();
          })
          .finally(() => {
            form_loading.value = false;
          });
      } else {
        form_loading.value = true;
        obj.envPath = form_params.envPath;
        obj.envName = form_params.envName;
        obj.envValue = form_params.envValue;
        obj.default = form_params.default;
        obj.envOriginName = form_params.envOriginName;
        AdminEnvironmentEdit(obj)
          .then((res) => {
            handleDialogClose();
            ElMessage.success("环境编辑成功");
            handleSearchList();
          })
          .finally(() => {
            form_loading.value = false;
          });
      }
    }
  });
};
const handleDefaultChange = (item) => {
  let text = "默认";
  if (item.default) text = "不默认";
  ElMessageBox.confirm(
    `确定要将该环境的默认状态修改为 ${text} 吗？`,
    "温馨提示",
    {
      confirmButtonText: "确 定",
      cancelButtonText: "取 消",
      type: "warning",
    }
  )
    .then(() => {
      const obj = {
        envPath: item.envPath,
        default: item.default == true ? false : true,
        envName: item.envName,
        envValue: item.envValue,
      };
      AdminEnvironmentEdit(obj).then((res) => {
        ElMessage.success("环境状态编辑成功");
        handleSearchList();
      });
    })
    .catch(() => {});
};
const handleDelete = (item) => {
  ElMessageBox.confirm(`确定要删除将该环境吗？`, "温馨提示", {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "warning",
  })
    .then(() => {
      let obj = {
        envName: item.envName,
      };
      AdminEnvironmentDelete(obj).then((res) => {
        ElMessage.success("环境删除成功");
        handleSearchList();
      });
    })
    .catch(() => {});
};

const handleCodemirrorChange = (value) => {
  form_params.envValue = value;
};
const handleYamlError = (value) => {
  yaml_error.value = value;
};
const handleExample = () => {
  let example_text = `
  # 定义 Service
  apiVersion: v1
  kind: Service
  metadata:
    name: cloudypytest-java-service
    namespace: kube-k8spytest
    labels:
      app: cloudypytest-java
  spec:
    selector:
      app: cloudypytest-java
    ports:
      - protocol: TCP
        port: 9000
        targetPort: 9000
  `;
  if (!form_params.envValue) {
    form_params.envValue = example_text;
  } else {
    ElMessageBox.confirm(
      "该操作会将现有的配置覆盖，确定要替换吗?",
      "温馨提示",
      {
        type: "warning",
      }
    )
      .then(() => {
        form_params.envValue = example_text;
      })
      .catch(() => {});
  }
};
</script>
<style scoped lang="scss">
.main_block {
  height: 100%;
  width: 100%;
  background-color: #fff;
  padding: 10px;
}
.search_item {
  width: 200px;
  margin-right: 8px;
}
.example {
  color: var(--el-color-primary);
  cursor: pointer;
}
</style>
